package com.hitqz.robot.biz.config;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.io.File;
import java.sql.Statement;

/**
 * @author xupkun
 * @date 2024/5/20
 */
@Slf4j
@Service
@AutoConfigureAfter(DataSource.class)
public class H2DataSourceConfig {

    @Value("${db.schema-location}")
    private String schemaLocation;

    @Value("${db.lock-file}")
    private String lockFile;

    @Autowired
    DataSource dataSource;

    @PostConstruct
    public void init() throws Exception {
        File f = new File(lockFile);
        log.info("数据库文件地址:{}", schemaLocation);
        if (!f.exists()) {
            log.info("database file userDir {}", schemaLocation);
            File file = new File(schemaLocation);
            if (file.isDirectory()) {
                for (File sqlFile : file.listFiles()) {
                    if (sqlFile.getAbsolutePath().endsWith(".sql")) {
                        log.info("数据库文件： {}, {}", sqlFile.getAbsolutePath(), sqlFile.exists());
                        try {
                            Statement statement = dataSource.getConnection().createStatement();
                            String sqlContent = FileUtils.readFileToString(sqlFile, "UTF-8");
                            statement.execute(sqlContent);
                            log.info("执行数据库文件成功：" + sqlFile.getAbsolutePath());
                        } catch (Exception e) {
                            log.info("执行数据文件失败: {}, {}", sqlFile.getAbsolutePath(), e.getMessage());
                        }
                    }
                }
                f.createNewFile();
            }
        }
    }
}
